package com.gz.controller;

import com.gz.dto.TuserDto;
import com.gz.entity.RoleInfo;
import com.gz.entity.Suser;
import com.gz.entity.Tuser;
import com.gz.entity.UserRole;
import com.gz.service.SuserService;
import com.gz.service.UserRoleService;
import com.gz.utils.DataFmtUtil;
import com.gz.vo.BaseRS;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.gz.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.gz.dto.SuserDto;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 学生用户表(Suser)表控制层
 *
 * @author makejava
 * @since 2024-05-29 13:46:18
 */
@RestController
@RequestMapping("suser")
@Api(value = "学生控制层", tags = {"学生控制层"})
public class SuserController {
    /**
     * 服务对象
     */
    @Autowired
    private SuserService suserService;
    /**
     * 服务对象
     */
    @Autowired
    private UserRoleService userRoleService;

    /**
     * 分页查询
     *
     * @param dto 筛选条件
     * @return 查询结果
     */
    @ApiOperation(value = "分页查询")
    @PostMapping("/queryPage")
    public R queryByPage(@RequestBody SuserDto dto, HttpServletRequest request) {
        return R.ok(suserService.queryByPage(dto));
    }

    /**
     * 分页查询
     *
     * @param dto 筛选条件
     * @return 查询结果
     */
    @ApiOperation(value = "条件查询")
    @PostMapping("/queryAll")
    public R queryAll(@RequestBody SuserDto dto, HttpServletRequest request) {
        dto.setToken(null);
        return R.ok(suserService.queryAll(dto));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation(value = "主键查询")
    @GetMapping("/queryById")
    public R<Suser> queryById(@RequestParam("id") Integer id) {
        return R.ok(suserService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param suser 实体
     * @return 新增结果
     */
    @ApiOperation(value = "新增数据")
    @PostMapping("/save")
    public R<Suser> add(@RequestBody Suser suser) {
        if (StringUtils.isEmpty(suser.getUsername())) {
            return R.failure("用户名不能为空");
        }
        if (StringUtils.isEmpty(suser.getPassword())) {
            return R.failure("密码不能为空");
        }
        if(!StringUtils.isEmpty(suser.getUsername())){
            SuserDto dto = new SuserDto();
            dto.setUsername(suser.getUsername());
            List<Suser> susers = suserService.queryAll(dto);
            if(CollectionUtils.isNotEmpty(susers)){
                return R.failure("该用户名已被注册");
            }
        }
        suser.setCrtDt(new Date());
        suser.setOptDt(new Date());
        try {
            /** 设置过期时间 */
            suser.setValidDate(DataFmtUtil.getDayAf120());
        } catch (ParseException e) {
            return R.failure("获取有效截止时间失败");
        }
        suser.setRoleId(3);
        Suser insert = suserService.insert(suser);
        List<Integer> roleIds = suser.getRoleIds();
        List<UserRole> userRoles = new ArrayList<>();
        roleIds.forEach(a -> {
            UserRole userRole = new UserRole();
            userRole.setUserId(insert.getId());
            userRole.setRoleId(a);
            userRoles.add(userRole);
        });
        userRoleService.insertBatch(userRoles);
        return R.ok(insert);
    }

    /**
     * 新增数据
     *
     * @param batchData 集合
     * @return 新增结果
     */
    @ApiOperation(value = "批量新增数据")
    @PostMapping("/saveBatch")
    public R<Integer> addBatch(@RequestBody List<Suser> batchData) {
        return R.ok(suserService.insertBatch(batchData));
    }

    /**
     * 编辑数据
     *
     * @param suser 实体
     * @return 编辑结果
     */
    @ApiOperation(value = "编辑数据")
    @PostMapping("/update")
    public R<Suser> edit(@RequestBody Suser suser) {
        return R.ok(suserService.update(suser));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @GetMapping("/deleteById")
    @ApiOperation(value = "删除数据")
    public R<Boolean> deleteById(@RequestParam("id") Integer id) {
        return R.ok(suserService.deleteById(id));
    }

    @PostMapping(value = "/login")
    @ApiOperation(value = "用户登录接口", notes = "用户登录接口")
    @ApiResponses({
            @ApiResponse(code = 200, message = "OK", response = Suser.class),
    })
    public BaseRS login(@RequestBody Suser user, HttpServletRequest request,
                        HttpServletResponse response) {
        SuserDto u = new SuserDto();
        u.setUsername(user.getUsername());
        List<Suser> users1 = suserService.queryAll(u);
        u.setPassword(user.getPassword());
        List<Suser> users2 = suserService.queryAll(u);
        if (CollectionUtils.isEmpty(users1)) {
            return BaseRS.builder().data(null).code("300").msg("未查找到该用户，请注册").build();
        } else {
            if (CollectionUtils.isEmpty(users2) || StringUtils.isEmpty(user.getPassword())) {
                return BaseRS.builder().data(null).code("301").msg("密码不能为空或密码错误").build();
            } else {
                Suser suser = users2.get(0);
                suser.setPassword(null);
                /** 查询角色信息 */
                return BaseRS.builder().data(suser).code("200").msg("success,登录成功").build();
            }
        }
    }
}

